
-- Main tables
local handlers, session, history = {}, {}, {};

-- Timer to count seconds
local timer = 0;

history = {
  time      = 0,
  dps       = 0,
  damage    = 0,
  criticals = 0,
  parries   = 0,
  dodges    = 0,
  misses    = 0,
  healing   = 0
};

session = {
  time      = 0,
  dps       = 0,
  damage    = 0,
  criticals = 0,
  parries   = 0,
  dodges    = 0,
  misses    = 0,
  healing   = 0
};

-- Reset given table counters
local function resetData(target)
  for key, value in pairs(target) do
    target[key] = 0;
  end
end

-- Entering combat
function handlers:PLAYER_REGEN_DISABLED(...)
end

-- Quitting combat
function handlers:PLAYER_REGEN_ENABLED(...)
end

-- Each combat action
function handlers:UNIT_COMBAT(...)
  if not InCombatLockdown() then return end

  unitID, action, descriptor, damage, damageType = unpack({...});

  if unitID == "target" and action == "WOUND" then
    history.damage = history.damage + damage;

    if descriptor == "CRITICAL" then
      history.criticals = history.criticals + 1;
    end
  elseif unitID == "player" and action == "PARRY" then
    history.parries = history.parries + 1;
  elseif unitID == "player" and action == "MISS" then
    history.misses = history.misses + 1;
  elseif unitID == "player" and action == "DODGE" then
    history.dodges = history.dodges + 1;
  elseif unitID == "player" and action == "HEAL" then
    history.healing = history.healing + damage;
  end

  DameterFrameDamage:SetText(history.damage);
  DameterFrameCriticals:SetText(history.criticals);
  DameterFrameHealing:SetText(history.healing);
  DameterFrameParries:SetText(history.parries);
  DameterFrameDodges:SetText(history.dodges);
  -- DameterFrameDamage:SetText(history.misses);
end

-- End of event handlers

function DameterFrame_OnLoad(self)
  self:RegisterForDrag("LeftButton");

  for e, handler in pairs(handlers) do
    self:RegisterEvent(e);
  end
end

function DameterFrame_OnEvent(self, event, ...)
  handlers[event](self, ...);
end

function DameterFrame_OnUpdate(self, elapsed)
  if InCombatLockdown() then
    timer = timer + elapsed;

    if timer >= 1 then
      timer = 0;
      
      history.time = history.time + 1;
      history.dps = math.floor(history.damage / history.time);

      DameterFrameDPS:SetText(history.dps);
      DameterFrameTime:SetText(history.time);
    end
  end
end
